package com.xoa.controller.dutyManagement;

import com.xoa.model.dutyManagement.DutyForm;
import com.xoa.model.users.Users;
import com.xoa.service.dutyManagement.DutyFormService;
import com.xoa.service.sms.SmsService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.dataSource.ContextHolder;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 值班表管理
 * author:殷冬
 * time:2018.05.12
 * vision:1.0.0
 */
@Controller
@Scope(value = "prototype")
@RequestMapping("/dutyManagement")

public class DutyFormController {
    @Resource
    private DutyFormService dutyFormService;

    @Resource
    SmsService smsService;


    /**
     *  值班管理主页面跳转
     *  author:殷冬
     *  time:2018.05.12
     *  vision:1.0.0
     */
    @RequestMapping("/pageJumpDutyManagement")
    public String returnDutyManagement(HttpServletRequest request){
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/dutyManagement/dutyManagement";
    }
    /**
     *  值班管理主页面跳转
     *  author:殷冬
     *  time:2018.05.12
     *  vision:1.0.0
     */
    @RequestMapping("/transactionRemind")
    public String transactionRemind(HttpServletRequest request){
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);

        String bodyId=request.getParameter("bodyId");
        if(!StringUtils.checkNull(bodyId)){
            smsService.setSmsReadByBodyId(request,Integer.valueOf(bodyId));
        }
        return "app/dutypoliceusers/transactionRemind";
    }
    /**
     *  值班管理副页面跳转
     *  author:殷冬
     *  time:2018.05.12
     *  vision:1.0.0
     */
    @RequestMapping("/dutyFormManagementList")
    public String returnDutyFormManagementList(HttpServletRequest request){
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/dutyManagement/dutyFormManagementList";
    }

    /**
     *  新建值班管理页面跳转
     *  author:殷冬
     *  time:2018.05.12
     *  vision:1.0.0
     */
    @RequestMapping("/dutyFormManagementAdd")
    public String returnDutyFormManagementAdd(HttpServletRequest request){
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/dutyManagement/dutyFormManagementAdd";
    }
    /**
     *  跳转到查看详情页面（通用）
     *  author:殷冬
     *  time:2018.05.12
     *  vision:1.0.0
     */
    @RequestMapping("returnSelDutyFormManagement")
    public String returnSelDutyFormManagement(Integer dutyId,HttpServletRequest request){
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        Users name= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        String userId = name.getUserId();
        String remindUrl = "/dutyManagement/returnSelDutyFormManagement?dutyId="+dutyId;
        //根据路径查询出sms_body中的body_id
        Integer bodyId = dutyFormService.getSmsBodyBodyId(remindUrl);
        //根据主键id和当前用户id修改sms数据状态为未读
        dutyFormService.updSmsByUserIdAndBodyId(userId,bodyId);
        return "app/dutyManagement/selDutyFormById";
    }
    /**
     * 值班信息列表跳转页面
     *  author:殷冬
     *  time:2018.05.13
     *  vision:1.0.0
     */
    @RequestMapping("dutyFormManagementSel")
    public String dutyFormManagementSel(HttpServletRequest request){
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        return "app/dutyManagement/dutyFormList";
    }
    /**
     * 添加值班信息表
     * author:殷冬
     * time:2018-05-12
     * visiion:1.0.0
     */
    @ResponseBody
    @RequestMapping("/addDutyFormManagement")
    public ToJson<DutyForm> addDutyFormManagement(DutyForm dutyForm, HttpServletRequest request){
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        Users name= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        dutyForm.setFormId(name.getUserId());
        dutyForm.setFormDept(name.getDeptId());
        dutyForm.setDateTime(((int)(System.currentTimeMillis()/1000))+"");
        ToJson<DutyForm> toJson = new ToJson<DutyForm>();
        int result = dutyFormService.addDutyFormManagement(request,dutyForm);
        if(result>0){
            toJson.setFlag(0);
            toJson.setMsg("success");
        }else{
            toJson.setFlag(1);
            toJson.setMsg("err");
        }
        return toJson;
    }

//    /**
//     *  查询全部的信息
//     *  author:殷冬
//     *  time:2018-05-12
//     *  vision:1.0.0
//     */
//    @ResponseBody
//    @RequestMapping("/getDutyFormManagementList")
//    public ToJson<DutyForm> getDutyFormManagementList(@RequestParam(name = "page", required = false, defaultValue = "1") Integer page,
//                                                      @RequestParam(name = "pageSize", required = false, defaultValue = "5") Integer pageSize,
//                                                      @RequestParam(name = "useFlag", required = false, defaultValue = "true")  Boolean useFlag,
//                                                       HttpServletRequest request, HttpServletResponse response){
//        ContextHolder.setConsumerType("xoa" + (String) request.getSession().getAttribute("loginDateSouse"));
//        Users user=SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
//        Map<String,Object> map = new HashMap<String,Object>();
//        ToJson<DutyForm> toJson = dutyFormService.getDutyFormManagementList(map,page,pageSize,useFlag,user);
//        return toJson;
//    }

    /**
     *  查询全部的信息
     *  author:殷冬
     *  time:2018-05-12
     *  vision:1.0.0
     */
    @ResponseBody
    @RequestMapping("/getDutyFormManagementList")
    public ToJson<DutyForm> getDutyFormManagementList(@RequestParam("page") Integer page,
                                                      @RequestParam("pageSize") Integer pageSize,
                                                      @RequestParam("useFlag") boolean useFlag,
                                                      HttpServletRequest request, HttpServletResponse response){
        ContextHolder.setConsumerType("xoa" + (String) request.getSession().getAttribute("loginDateSouse"));
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        Map<String,Object> map = new HashMap<String,Object>();
        List<DutyForm> list = dutyFormService.getDutyFormManagementAll();
        ToJson<DutyForm> toJson = dutyFormService.getDutyFormManagementList(map,page,pageSize,useFlag,user,list);
        return toJson;
    }
    /**
     *  查询当前登录用户发布的信息
     *  author:殷冬
     *  time:2018-05-12
     *  vision:1.0.0
     */
    @ResponseBody
    @RequestMapping("/getDutyFormManagementListByUserId")
    public ToJson<DutyForm> getDutyFormManagementListByUserId(@RequestParam(name = "page", required = false, defaultValue = "1") Integer page,
                                                              @RequestParam(name = "pageSize", required = false, defaultValue = "5") Integer pageSize,
                                                              @RequestParam(name = "useFlag", required = false, defaultValue = "true")  Boolean useFlag,
                                                              HttpServletRequest request, HttpServletResponse response){
        ContextHolder.setConsumerType("xoa" + (String) request.getSession().getAttribute("loginDateSouse"));
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        Map<String,Object> map = new HashMap<String,Object>();
        ToJson<DutyForm> toJson = dutyFormService.getDutyFormManagementListByUserId(map,page,pageSize,useFlag,user);
        return toJson;
    }
    /**
     * 根据主键id查询
     * author:殷冬
     * time:2018-05-12
     * vision:1.0.0
     */
    @ResponseBody
    @RequestMapping("getDutyFormById")
    public DutyForm getDutyFormById(Integer dutyId, HttpServletRequest request){
        ContextHolder.setConsumerType("xoa" + (String) request.getSession().getAttribute("loginDateSouse"));
        String sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        ContextHolder.setConsumerType(sqlType);
        return dutyFormService.getDutyFormById(request,dutyId,sqlType);
    }
    /**
     * 根据主键删除
     * author:殷冬
     * time:2018-05-12
     * vision:1.0.0
     */
    @ResponseBody
    @RequestMapping("delDutyFormById")
    public boolean delDutyFormById(Integer dutyId,HttpServletRequest request){
        ContextHolder.setConsumerType("xoa" + (String) request.getSession().getAttribute("loginDateSouse"));
        return dutyFormService.delDutyFormById(dutyId);
    }
    /**
     * 根据主键修改
     * author:殷冬
     * time:2018-05-13
     * vision:1.0.0
     */
    @ResponseBody
    @RequestMapping("dutyFormManagementUpdate")
    public boolean updDutyFormById(DutyForm dutyForm,HttpServletRequest request){
        ContextHolder.setConsumerType("xoa" + (String) request.getSession().getAttribute("loginDateSouse"));
        dutyForm.setDateTime(((int)(System.currentTimeMillis()/1000))+"");
        return dutyFormService.updDutyFormById(dutyForm);
    }
    /**
     * 删除全部值班表
     * author:殷冬
     * time:2018-05-13
     * vision:1.0.0
     */
    @ResponseBody
    @RequestMapping("delDutyFormAll")
    public boolean delDutyFormAll(HttpServletRequest request){
        ContextHolder.setConsumerType("xoa" + (String) request.getSession().getAttribute("loginDateSouse"));
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        return dutyFormService.delDutyFormAll(user);
    }
    /**
     * 删除选中的值班表
     * author:殷冬
     * time:2018-05-13
     * vision:1.0.0
     */
    @ResponseBody
    @RequestMapping("delDutyFormByDutyIds")
    public boolean delDutyFormByDutyIds(@RequestParam("dutyIds[]") String[] dutyIds, HttpServletRequest request){
        ContextHolder.setConsumerType("xoa" + (String) request.getSession().getAttribute("loginDateSouse"));
        return dutyFormService.delDutyFormByDutyIds(dutyIds);
    }
    /**
     * 导出excel表格
     * author:殷冬
     * time:2018-05-13
     * vision:1.0.0
     */
    @ResponseBody
    @RequestMapping("reportDutyForm")
    public void reportDutySituation(HttpServletRequest request, HttpServletResponse response) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Map<String,Object> maps = new HashMap<String,Object>();
        HSSFWorkbook workbook2 = new HSSFWorkbook();
        workbook2.createSheet();
        String[] secondTitles = {"开始时间","结束时间"};
        HSSFSheet sheet = workbook2.getSheetAt(0);
        HSSFRow rowField = sheet.createRow(0);
        for (int i = 0; i < secondTitles.length; i++) {
            HSSFCell cell = rowField.createCell(i);
            cell.setCellValue(secondTitles[i]);
        }
        String[] beanProperty = {"startTime","endTime"};
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        List<DutyForm> dutySituationList = dutyFormService.getDutyFormListRep(maps,user);
        HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2,dutySituationList,beanProperty);

        try (ServletOutputStream out = response.getOutputStream()){
        String filename = "值班表.xls";
        filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-disposition", "attachment;filename=" + filename);
        workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 导出excel表格 当前登录用户发布的
     * author:殷冬
     * time:2018-05-13
     * vision:1.0.0
     */
    @ResponseBody
    @RequestMapping("reportDutyFormByUserId")
    public void reportDutyFormByUserId(HttpServletRequest request, HttpServletResponse response) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Map<String,Object> maps = new HashMap<String,Object>();
        HSSFWorkbook workbook2 = new HSSFWorkbook();
        workbook2.createSheet();
        String[] secondTitles = {"开始时间","结束时间"};
        HSSFSheet sheet = workbook2.getSheetAt(0);
        HSSFRow rowField = sheet.createRow(0);
        for (int i = 0; i < secondTitles.length; i++) {
            HSSFCell cell = rowField.createCell(i);
            cell.setCellValue(secondTitles[i]);
        }
        String[] beanProperty = {"startTime","endTime"};
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        List<DutyForm> dutySituationList = dutyFormService.reportDutyFormByUserId(maps,user);
        HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2,dutySituationList,beanProperty);

        try ( ServletOutputStream out = response.getOutputStream()){
        String filename = "值班表.xls";
        filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-disposition", "attachment;filename=" + filename);
        workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //有权限的列表
    @ResponseBody
    @RequestMapping("/getDutyFormList")
    public ToJson getList(HttpServletRequest request, HttpServletResponse response, String exportId, Integer page, Integer pageSize, boolean useFlag){

        return dutyFormService.getDutyFormList(request,response,Integer.parseInt(exportId),  page,  pageSize, useFlag);
    }
}
